Creating Modules

This is easy.

Things to know

  1. How to import
  2. For now, files to import must be in the same directory as the file where you are importing to
  3. Calling functions from the imported file

Hands On

  1. Open the command line to this directory
  2. Enter into the python shell by typing 'python'
  3. Inside the python shell and run 'import first_module' --- you dont need to add the extension at the end
  4. Then run each function in the module
Example

In [ ]:
first_module.magic()

Explanation

We are importing a module called first_module, by now you should know what we mean by importing. Then we are calling functions inside the module we imported. Pls take note of how we imported the module.

Notes
  1. We did not add the extension of the module because it is not needed.
  2. We accessed the functions inside the module by calling the function through the module name on the import - meaning that because we imported first_module it is first_module that we will use to access the functions inside the module. if the module were to have a different name eg. import go_module, it is go_module we will use to access the functions and properties defined in the go_module

Naming our Modules on import

We can give our modules a different name on import.

Hands On

  1. Open the command line to the directory where you have the first_module.py
  2. Then enter in to the python shell
  3. Then run 'import first_module as fm'
  4. Access functions inside first_module like this

In [ ]:
fm.magic()

This should give the same result as first_module.magic() because only gave first_module another name (like an a.k.a) by using the 'as' on our import statement

Read More

Research more about import statements

Practice

  1. Create a file and call it function_module.py
  2. Inside functions.py define 5 functions that prints anything you want to the console
  3. Create another file and call it script.py
  4. Inside script.py, import your function_module.py (you can use the 'as' on the import to give the import statement a name you want
  5. After the import statement, make a call to all the functions you have defined in the function_module.py

Note

For more help contact us on the group, Thanks

Next

Beautiful Soup and Web Scraping